package com.zixuan.sina.config.security;
import com.zixuan.sina.entity.Permission;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.service.PermissionService;
import com.zixuan.sina.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户认证处理器类
 */
@Component
public class CommonUserDetailsService implements UserDetailsService {
    @Resource
    UserService userService;
    @Resource
    PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUsername(username);
        if(ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //用户鉴权
        List<Permission> permissionList = permissionService.findPermissionByUserId(user.getId());
        //过滤出code
        List<String> codeList = permissionList.stream()
                .filter(Objects::nonNull)
                .map(Permission::getCode)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        String[] code =codeList.toArray(new String[codeList.size()]);
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(code);//将过滤出来的code放入用户角色列表中
        user.setAuthorities(authorities);
        user.setPermissionList(permissionList);
        return user;
    }
}
